package com.example;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;


public class ServerThread implements Runnable, Message {

    private Socket socket;
    private InputStream is;
    private OutputStream os;
    private Map<User, Socket> userMap;
    private int ID;
    private ServerClient sc;
    private List<User> userList;


    public ServerThread(Socket socket, Map<User, Socket> userMap, int ID, List<User> userList) {
        this.socket = socket;
        this.userMap = userMap;
        this.ID = ID;
        this.userList = userList;


        try {
            is = socket.getInputStream();
            os = socket.getOutputStream();
            this.sc = new ServerClient(socket);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                int head = is.read();
                String sMsg = sc.readMsg(is);
                System.out.println("head:" + head + "  msg = " + sMsg);
                String[] msgArr = sMsg.split(":");
                switch (head) {
                    case LOGIN:

                        login(msgArr[0], msgArr[1]);
                        break;
                    case REGISTER:

                        break;
                    case PRIVATE:
                        privateChat(msgArr);
                        break;
                }

                System.out.println("发送数据成功！！！");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public void login(String user, String pass) throws Exception {



        for (User u : userList) {
            if (user.equals(u.getUser()) && pass.equals(u.getPass())) {
                userMap.put(u,socket);
                sc.success();
                return;
            }
        }

        sc.error();
    }


    public void register(String user, String pass) throws Exception {

    }


    public void privateChat(String[] msgArr) throws Exception {
        for (Map.Entry<User, Socket> entry : userMap.entrySet()) {
            if (msgArr[0].equals(entry.getKey() + "")) {
                Socket socket = entry.getValue();
                OutputStream output = socket.getOutputStream();
                sc.sendMsg(output, msgArr[1]);
            }
        }
    }
}
